#include "drv_PrivateTimer_ostick.h"

void corePrivateTimerISR(int vector, void *param)
{
    rt_interrupt_enter();

    rt_tick_increase();

    REG_CORE_PTIMER_INT_STAT = 1;   // 写1对中断标志清零

    rt_hw_interrupt_ack(PTIMER_IRQ_NUMBER);

    rt_interrupt_leave();
}

// 内部私有定时器初始化函数
void corePrivateTimerInit(void)
{
    const rt_uint32_t precale = 249 ;       // 预分频器值
    const rt_uint32_t periphCLK = 500;   // 晶振频率 单位MHz

    rt_uint32_t timerLoadValue = 0;  // 装载值
    rt_uint32_t timerInterval = 0;    //定时时间 单位 us

    REG_CORE_PTIMER_CTRL = 0;   // 停止定时器

    // 括号内单位为ms ×1000后得到 us
    timerInterval = (1000 / (rt_uint32_t)RT_TICK_PER_SECOND) * 1000;  
    // 根据公式计算装载时间
    timerLoadValue = ((timerInterval * periphCLK) / (precale + 1)) - 1 ;


    REG_CORE_PTIMER_LOAD = timerLoadValue;
    REG_CORE_PTIMER_VALUE = timerLoadValue;
    REG_CORE_PTIMER_INT_STAT = 1;   // 写1对中断标志清零

    rt_hw_interrupt_install(PTIMER_IRQ_NUMBER, corePrivateTimerISR, RT_NULL, "tick");
    rt_hw_interrupt_umask(PTIMER_IRQ_NUMBER);

    // 装入预分频值 IRQ使能 自动重装使能 定时器使能 
    REG_CORE_PTIMER_CTRL = (precale<<8) | 0x07 ;
    // 打开irq中断 
    asm volatile ("cpsie i");
    return ;
}

